package controllers;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.joda.time.DateTime;
import org.joda.time.Days;

import models.Episode;
import models.Serie;
import models.User;
import play.mvc.With;

import common.FBSecure;

@With(FBSecure.class)
public class Schedule extends FBController {
	
	
	
    public static void index(Long id, String from, String to) {
        
    	setFbIdandName();
    	
    	User user = null;
    	
    	if (id != null) {
    		user = User.findById(id);
    	}
    	
    	int days = 7;
    	
    	Date date1 = new Date();
    	
    	if (from != null && to != null) {
    		try {
				date1 = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(from);
				Date date2 = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(to);
				days = Days.daysBetween(new DateTime(date1), new DateTime(date2)).getDays() + 1;
			} catch (ParseException e) { }
    	}
    	
    	List<List<Episode>> episodes = new ArrayList<List<Episode>>();
  
    	Calendar c = Calendar.getInstance();
    	c.setTime(date1);
    	
    	for (int i=0; i<days; i++) {
    		
    		List<Episode> eps = Episode.upcomingEpisodes(c.getTime());
    		
    		c.add(Calendar.DATE, 1);
    		
    		if (user == null && eps.size() > 0)
    			episodes.add(eps);
    		
    		if (user != null && eps.size() > 0) {
    			
    	    	List<Serie> follows = user.getFollows();
    	    	List<Episode> followEpisodes = new ArrayList<Episode>();
    	    	
        		for (Episode episode : eps) {
        			for (Serie s : follows) {
        				if (s.getId().equals(episode.getSerie().getId())) {
        					followEpisodes.add(episode);
        					break;
        				}
        			}
        		}
        		
        		if (followEpisodes.size() > 0) {
        			episodes.add(followEpisodes);
        		}
        	}
    	}
    	
    	
    	render(episodes, from, to, user);
    }
    
    

}
